<?php
defined('SYSPATH') or die ('No direct access allowed.');

/**
 *不合格采购处理页面模块,查询，修改
 * handlequality
 * @author cxy
 */
class Controller_unqualified extends Template
{
    protected $user; //登陆用户的ID
    protected $recieve_man; //登陆用户的名字

    public function before()
    {
        $userid            = User::active_user()->id;
        $this->user        = $userid;
        $username          = ORM::factory('user')
            ->where('id','=',$userid)
            ->find();
        $this->recieve_man = $username->name;
        try{
            ACL::Required('unqualified');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        parent::before();
    }

    //首页
    public function action_index()
    {
        $this->title = '不良品处理';
        $userId      = USER::Active_user()->id;
        $view        = View::factory('unqualified/unqualified');
        $way         = DB::select('number','value')
            ->from('statusdics')
            ->where('table','=','unqualified_deal_invoices')
            ->where('colum_name','=','fail_deal_way')
            ->execute('newerp')
            ->as_array();
        $operate_man = Erpuser::nick_by_id($userId);
        $sta         = DB::select('number','value')
            ->from('statusdics')
            ->where('table','=','unqualified_deal_invoices')
            ->where('colum_name','=','status')
            ->execute('newerp')
            ->as_array();
        $view->way   = $way;
        $view->sta   = $sta;
        $view->set('operate_man_name',$operate_man);
        $this->response->body($view);
    }

    //点击详情后修改和处理不良产品的动作
    public function action_unqualified_check()
    {
        $this->title = '不良品处理';

        $arr = array();
        if(isset($_POST['id'])){
            $array = $_POST['chuli'];
            $re    = array();
            //每次点击提交后我就会去查找这个单号的实际库存
            $have_ins   = $have_outs = 0;
            $inquantity = DB::select_array(array(
                'quantity',
                'store',
                'warehouseid'
            ))
                ->from('unqualified_deal_invoices')
                ->where('id','=',$_POST['id'])
                ->execute('newerp')
                ->current();
            $have_ins   = $inquantity['quantity'];
            
            if($_POST['inputs']>$have_ins){
                echo json_encode(10);
                exit;
            }
            $unqualified_total = $_POST['quantity']; //不合格数量
            if($_POST['vProviderName']){
                $arr['supplier'] = Basic::getidByName($_POST['vProviderName']);
            }else{
                $arr['supplier'] = 0;
            }
            //$arr['id']               = rand(-999999999,-1);
            $arr['purchaseorder_id'] = $_POST['purchaseorder_id'];
            $arr['sku']              = $_POST['sku'];
            $arr['operate_man']      = $this->user;
            $arr['unqualified_id']   = $_POST['id'];
            $arr['sku_name']         = $_POST['sku_name'];
            $arr['deal_time']        = date('Y-m-d H:i:s');
            $arr['check_detail_id']  = $_POST['check_detail_id'];
            $arr['store']            = $inquantity['store'];
            $purid                   = qualitycomm::getunqualityid($_POST['id']);
            $count                   = 0;
            $aa                      = 0;

            if(count($array)>0){
                foreach($array as $k => $arr_s){

                    if($arr_s['quality_count']!=NULL){

                        $arr['quantity']           = $arr_s['quality_count'];
                        $arr['fail_deal_way']      = $arr_s['way_zong'];
                        $arr['unqualified_reason'] = $arr_s['remark'];
                        $arr['coupon_price']       = $arr_s['coupon_price'];
                        $arr['return_cost']        = $arr_s['return_cost'];
                        $arr['purchase_man']       = $purid;
                        $arr['warehouseid']        = $inquantity['warehouseid'];
                        $count += $arr['quantity'];
                        //$arr_s['bad_id']为0或者空的时候说明不良品出库表里没有这个记录
                        if($arr_s['bad_id']==0||$arr_s['bad_id']==NULL){
                            $db             = comm::insert_recieveinvoices('bad_product_delivery',$arr);
                            $re['insert'][] = $db[0];
                            /*
                            $aid            = $db[0];
                            if(!empty($aid)){
                                $id  = (int)((string)$aid.sprintf("%03d",$arr['warehouseid']));
                                $sql = "UPDATE `bad_product_delivery` SET `id` =".$id." WHERE `aid` =".$aid;
                                $dat = DB::query(Database::UPDATE,$sql);
                                $row = $dat->execute('newerp');
                            }
                            */

                            
                        }else{
                            $select = qualitycomm::select_bad_product_delivery('status',$arr_s['bad_id']);
                            if($select['status']==10){
                                $update = qualitycomm::update_bad_product_delivery_byid($arr_s['bad_id'],$arr);
                                //echo json_encode('成功更新'.$update);
                                //exit;
                                $re['update'][]['id'] = $arr_s['bad_id'];
                                if($update>0){
                                    $re['update'][]['update'] = 1;
                                }else{
                                    $re['update'][]['update'] = 0;
                                }
                            }else{
                                $re['update'][]['update'] = 0;
                            }
                        }
                        $r[] = $arr_s['quality_count'];
                    }
                }

                //输入的数量是否等于不合格数量
                if($count==$unqualified_total){
                    $result = ORM::factory('unqualifieddeal',$_POST['id'])//->values($_POST)
                        ->set('status',20)
                        ->set('operate_man',$this->user)
                        ->set('deal_time',date("Y-m-d H:i:s"))
                        ->save();
                }
                echo json_encode($re);
                exit;
            }
        }
    }

    //完结不合格产品的动作,旧方法，目前没用
    public function action_unqualified_end()
    {
        $this->title = '不良品处理完结';
        $result      = ORM::factory('unqualified',$_POST['id'])
            ->values($_POST)
            ->set('status',30)
            ->set('end_man',$this->user)
            ->set('end_time',date("Y-m-d H:i:s"))
            ->save();
        if($result->loaded()){
            if($_POST['fail_deal_way']==5){
                $result = qcwo::insert_wo($_POST['id']);
                echo json_encode(TRUE);
                exit;
            }
        }
        echo json(FALSE);
        exit;
    }

    //根据质检，供应商，日期，处理方式等的字段来查询
    public function action_unqualified_select()
    {
        $this->title = '不良品处理';
        $basic       = new Basic();
        if(!empty($_GET)){
            $way    = DB::select('number','value')
                ->from('statusdics')
                ->where('table','=','unqualified_deal_invoices')
                ->where('colum_name','=','fail_deal_way')
                ->execute('newerp')
                ->as_array();
            $sta    = DB::select('number','value')
                ->from('statusdics')
                ->where('table','=','unqualified_deal_invoices')
                ->where('colum_name','=','status')
                ->execute('newerp')
                ->as_array();
            $status = trim($_GET['status']);
            //$fail_deal_way=trim($_GET['fail_deal_way']);
            $condition = $_GET;
            //print_r($condition);exit;
            $orms       = DB::select()
                ->from('unqualified_deal_invoices')
                ->order_by('invoice_date','DESC');
            $result_all = unqualitydb::get_info($condition,$status,$orms);
            $count      = count($result_all);
            $pagination = Pagination::factory(array(
                'total_items'    => $count,
                //总记录数
                'items_per_page' => 20,
                //每页显示多少条
                'uri'            => $this->request->uri(),
            ));
            $orms->limit($pagination->items_per_page);
            $orms->offset($pagination->_offset);
            $result = $orms->execute('newerp')
                ->as_array();
            $view   = View::factory('unqualified/unqualified');
            foreach($result as $ks => $v){
                $result[$ks]['vProviderName'] = $basic->getnameByid($v['supplier']);
                if($v['operate_man']>0){
                    $result[$ks]['operater'] = Erpuser::nick_by_id($v['operate_man']);
                }else{
                    $result[$ks]['operater'] = '';
                }
                if($v['quality_man']>0){
                    $result[$ks]['quality_man_name'] = Erpuser::nick_by_id($v['quality_man']);
                }else{
                    $result[$ks]['quality_man_name'] = '';
                }

                if($v['purchase_man']>0){
                    $result[$ks]['purchaser'] = Erpuser::nick_by_id($v['purchase_man']);
                }else{

                    //20141229gqc tianjiachuliren
                    /*$nick_sql="select users.nick from user_skus as us
                    join gleez.users as users
                    on (us.user_id=users.id)
                    where us.sku='".$v['sku']."'
                    and us.isavailable=1
                    order by users.id desc
                    limit 1";
                    require_once(Kohana::find_file('vendor','phprpc/phprpc_client'));
                    $client = new PHPRPC_Client();
                    $client->useService("http://192.168.5.5:802/profitapi/execute");
                    $nick = json_decode($client->getinfo($nick_sql),true);

                    if($nick&&isset($nick[0]['nick']))
                        $result[$ks]['purchaser'] = $nick[0]['nick'];
                    else*/
                    $result[$ks]['purchaser'] = '';
                }
            }

            if($count==0){
                Message::error('你想查找的内容没有记录');
            }
            $page_links       = $pagination->render(); //渲染分页到模板
            $view->page_links = $page_links;
            $view->orm        = $result;
            $view->way        = $way;
            $view->sta        = $sta;
            //加一行计划员名字
            $view->operate_man       = isset($_GET['operate_man'])?$_GET['operate_man']:NULL;
            $view->purchase_man_name = isset($_GET['purchase_man_name'])?$_GET['purchase_man_name']:NULL;
            $view->supplier          = isset($_GET['supplier'])?$_GET['supplier']:NULL;
            $view->purchaseorder_id  = isset($_GET['purchaseorder_id'])?$_GET['purchaseorder_id']:NULL;
            $view->quality_man       = isset($_GET['quality_man'])?$_GET['quality_man']:NULL;
            $view->sku               = isset($_GET['sku'])?$_GET['sku']:NULL;
            $view->date_from_c       = isset($_GET['date_from_c'])?$_GET['date_from_c']:NULL;
            $view->date_to_c         = isset($_GET['date_to_c'])?$_GET['date_to_c']:NULL;
            $view->date_from         = isset($_GET['date_from'])?$_GET['date_from']:NULL;
            $view->date_to           = isset($_GET['date_to'])?$_GET['date_to']:NULL;
            $view->no_purchaseorder_id = isset($_GET['no_purchaseorder_id']) ? $_GET['no_purchaseorder_id']: 0;
            $view->status    = isset($_GET['status'])?$_GET['status']:NULL;
            $view->check_man = $this->recieve_man;
            $this->response->body($view);
        }else{
            $this->request->redirect("unqualified/index");
        }
    }

    //gqc20141230不良品处理允许添加修改供应商
    public function action_change_supplier()
    {
        $respons = '';
        if(isset($_GET['id'])&&$_GET['id']){
            $view = View::factory('unqualified/su_change');
            $view->set('un_id',$_GET['id']);
            $view->set('sku',$_GET['sku']);
            $respons = array("view" => $view->render());
        }

        if(isset($_POST['id']) and isset($_POST['su_name'])  and isset($_POST['sku']) and $_POST['su_name']){
            $id_sql = "select supplier_id from vmi_supplier_skus
                    where supplier_name='".$_POST['su_name']."'
                    and isavailable=1 and sku='".$_POST['sku']."'
                    limit 1";
            require_once(Kohana::find_file('vendor','phprpc/phprpc_client'));
            $ids = DB::query(Database::SELECT,$id_sql)
                ->execute('newerp')
                ->as_array();
            if($ids&&isset($ids[0]['supplier_id'])){
                $po_status = DB::update('unqualified_deal_invoices')
                    ->set(array('supplier' => $ids[0]['supplier_id']))
                    ->where('id','=',trim($_POST['id']))
                    ->execute('newerp');
                if($po_status){
                    $respons = array(
                        'code' => 200,
                        'mes'  => $po_status
                    );
                }
            }else{
                $respons = -1;
            }
        }
        echo is_array($respons)?json_encode($respons):$respons;
        exit;
    }

    //gqc20141230不良品处理允许添加修改计划员
    public function action_change_pu_man()
    {
        $respons = '';
        if(isset($_GET['id'])&&$_GET['id']){
            $view = View::factory('unqualified/pu_man_change');
            $view->set('un_id',$_GET['id']);

            $respons = array("view" => $view->render());
        }

        if(isset($_POST['id']) and isset($_POST['pu_man_name']) and $_POST['pu_man_name']){
            $user_id = DB::select('id')
                ->from('users')
                ->where('nick','like',"%".$_POST['pu_man_name']."%")
                ->limit(1)
                ->execute()
                ->get('id',0);

            if($user_id){
                $po_status = DB::update('unqualified_deal_invoices')
                    ->set(array('purchase_man' => $user_id))
                    ->where('id','=',trim($_POST['id']))
                    ->execute('newerp');
                if($po_status){
                    $respons = array(
                        'code' => 200,
                        'mes'  => $user_id
                    );
                }
            }
        }
        echo json_encode($respons);
        exit;
    }
}
